using System;
using System.Collections.Generic;
using System.Linq;
using Gameplay.PVE;
using UnityEditor.Rendering.Universal;
using UnityEngine;

namespace Yoozoo.Gameplay.Liberty
{
    [ExecuteAlways]
    public class GetLightmapComponent : MonoBehaviour
    {
        public List<MeshRendererData> meshRendererDataList;

        public Transform originRoot;

        private List<MeshRenderer> meshRenderers;
        
        public void GetLightmap()
        {
            if (originRoot != null)
            {
                List<MeshRenderer> meshRenderers = originRoot.GetComponentsInChildren<MeshRenderer>().ToList();
                meshRendererDataList = new List<MeshRendererData>();

                for (int i = 0; i < meshRenderers.Count; i++)
                {
                    var ms = meshRenderers[i];
                    MeshRendererData rendererData = new MeshRendererData();
                    rendererData.lightmapIndex = ms.lightmapIndex;
                    rendererData.renderIndex = i;
                    rendererData.lightmapScaleOffset = ms.lightmapScaleOffset;
                    meshRendererDataList.Add(rendererData);
                }

                originRoot = null;
            }
        }

        private void OnEnable()
        { 
            meshRenderers = GetComponentsInChildren<MeshRenderer>().ToList();
            SetLightmap();
            SetReflectionProbe();
        }
        public void SetLightmap()
        {
            if (meshRendererDataList!=null && meshRendererDataList.Count == meshRenderers.Count)
            {
                for (int i = 0; i < meshRenderers.Count; i++)
                {
                    var ms= meshRenderers[i];
                    ms.lightmapIndex = meshRendererDataList[i].lightmapIndex;
                    ms.lightmapScaleOffset = meshRendererDataList[i].lightmapScaleOffset;
                }
            }
        }
        
        private void SetReflectionProbe()
        {
            if (meshRenderers!=null)
            {
                foreach (var meshRenderer in meshRenderers)
                {
                    HReflectionProbeBakeRotated.OneObjWriteInShader(meshRenderer);
                }
            }
        }

    }
}